package org.jeecg.modules.demo.commoditymanagement.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.commoditymanagement.entity.CommodityInfo;
import org.jeecg.modules.demo.commoditymanagement.entity.CommodityManagement;
import org.jeecg.modules.demo.commoditymanagement.service.ICommodityManagementService;
import org.jeecg.modules.dmyweb.base.service.IBaseService;
import org.jeecg.modules.util.RedisUtils;
import org.jeecg.modules.util.ToolsUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品管理
 */
@Api(tags = "商品管理")
@RestController
@RequestMapping("/commoditymanagement/commodityManagement")
@Slf4j
public class CommodityManagementController extends JeecgController<CommodityManagement, ICommodityManagementService> {
    @Autowired
    private ICommodityManagementService commodityManagementService;
    @Autowired
    private IBaseService baseService;
    @Autowired
    private RedisUtils redisUtils;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "商品管理-分页列表查询")
    @ApiOperation(value = "商品管理-分页列表查询", notes = "商品管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CommodityManagement commodityManagement,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        QueryWrapper<CommodityManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
//        queryWrapper.eq("is_show", 1);
        // req.getParameterMap()被锁定无法删除元素，复制一份
        Map<String, String[]> pMap = new HashMap<>(req.getParameterMap());
        // status条件不走框架自带判断
        String[] statuses = pMap.remove("status");
        String status = statuses == null || statuses.length == 0 ? null : statuses[0];
        // status = 3时，只展示下架（售罄）的商品
        if ("3".equals(status)) {
            commodityManagement.setStatus("2");
            commodityManagement.setInventory(0);
        }
        String[] columns = pMap.get("column");
        String column = columns == null || columns.length == 0 ? null : columns[0];
        if (StringUtils.isEmpty(column) || "createTime".equals(column)) {
            // 没有排序条件时，默认用权重排序
            pMap.put("column", new String[]{"weight"});
            pMap.put("order", new String[]{"asc"});
        }
        QueryGenerator.initQueryWrapper(queryWrapper, commodityManagement, pMap);
        Page<CommodityManagement> page = new Page<>(pageNo, pageSize);
        IPage<CommodityManagement> pageList = commodityManagementService.page(page, queryWrapper);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<CommodityManagement> records = pageList.getRecords();
        // 做字典值翻译：status 1.上架2.下架，库存为0则为下架（售罄）
        List<Map<String, Object>> records1 = records.stream().map(cm -> {
            Map<String, Object> m = ToolsUtils.objectToMap(cm);
            Integer inventory = cm.getInventory();
            String status1 = cm.getStatus();
            if ("1".equals(status1)) {
                m.put("statusName", "上架");
            } else if ("2".equals(status1) && inventory > 0) {
                m.put("statusName", "下架");
            } else if ("2".equals(status1) && inventory == 0) {
                m.put("statusName", "下架（售罄）");
            }
            Date createTime = (Date) m.get("createTime");
            Date updateTime = (Date) m.get("updateTime");
            if (createTime != null) {
                m.put("createTime", sdf.format(createTime));
            }
            if (updateTime != null) {
                m.put("updateTime", sdf.format(updateTime));
            }
            return m;
        }).collect(Collectors.toList());
        IPage<Map<String, Object>> pageList1 = new PageDTO<>();
        BeanUtils.copyProperties(pageList, pageList1);
        pageList1.setRecords(records1);
        return Result.OK(pageList1);
    }

    /**
     * 分页列表查询
     */
    @AutoLog(value = "商品管理-搜索查询")
    @ApiOperation(value = "商品管理-搜索查询", notes = "商品管理-搜索查询")
    @PostMapping("/search")
    public Result<?> search(@RequestBody Map<String, Object> map, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        map.put("storeId", storeId);

        return Result.OK(commodityManagementService.search(map));
    }

    @AutoLog(value = "商品管理-分类查询")
    @ApiOperation(value = "商品管理-分类查询", notes = "商品管理-分类查询")
    @GetMapping(value = "/selfJson")
    public Result<?> selfJson(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String sql = "SELECT classification_goods as classificationGoods FROM commodity_management WHERE store_id = '" + storeId + "' GROUP BY classification_goods";
        List<Map<String, Object>> classifyList = baseService.getSqlQuery(sql);

        JSONObject obj = new JSONObject();
        JSONArray arrays = new JSONArray();
        int index = 0;

        for (Map<String, Object> bean : classifyList) {
            index++;
            String classify = String.valueOf(bean.get("classificationGoods"));
            JSONObject projectNames = new JSONObject();
            projectNames.put("id", index);
            projectNames.put("name", classify);
            JSONArray array = new JSONArray();
            if (oConvertUtils.isNotEmpty(classify)) {
                QueryWrapper<CommodityManagement> query = new QueryWrapper<>();
                query.eq("store_id", storeId);
                query.eq("classification_goods", classify);
                List<CommodityManagement> listData = commodityManagementService.list(query);
                for (CommodityManagement commodity : listData) {
                    JSONObject card = new JSONObject();
                    card.put("id", commodity.getId());
                    card.put("name", commodity.getTradeName());
                    card.put("content", commodity.getProductDescription());
                    card.put("url", commodity.getProductPic());
                    array.add(card);
                }

            }
            projectNames.put("card", array);
            arrays.add(projectNames);
        }
        obj.put("projectNames", arrays);
        return Result.OK(obj);
    }

    /**
     * 根据分组id查询商品列表（前端未使用）
     */
    @RequestMapping(value = "/getListByGroupId", method = RequestMethod.GET)
    public Result<List<CommodityInfo>> getListByGroupId(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "storeId", required = true) String storeId,
            @RequestParam(name = "groupId", required = true) String groupId) {
        Result<List<CommodityInfo>> result = new Result<>();
        List<CommodityInfo> list = commodityManagementService.getListByGroupId(pageNo, 10, storeId, groupId);
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }


    /**
     * 添加
     */
    @AutoLog(value = "商品管理-添加")
    @ApiOperation(value = "商品管理-添加", notes = "商品管理-添加")
    @PostMapping(value = "/add")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> add(@RequestBody CommodityManagement commodityManagement, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        commodityManagement.setStoreId(storeId);
        // 当前店铺全部商品
        List<CommodityManagement> list = commodityManagementService.list(new QueryWrapper<CommodityManagement>().eq("store_id", storeId));
        // list中与commodityManagement同名的商品个数
        long count = list.stream().filter(cm -> cm.getTradeName().equals(commodityManagement.getTradeName())).count();
        if (count > 0) {
            return Result.error("添加失败，该店铺已有同名商品！");
        }
        if (commodityManagement.getProductPrice() < 0) {
            return Result.error("添加失败，价格不能小于0！");
        }
        if (commodityManagement.getPriceCost() < 0) {
            return Result.error("添加失败，成本价不能小于0！");
        }
        if (commodityManagement.getGrossRate() < 0 || commodityManagement.getGrossRate() > 100) {
            return Result.error("添加失败，毛利率应在0-100范围内！");
        }
        if (commodityManagement.getMinimumMargin() < 0 || commodityManagement.getMinimumMargin() > 100) {
            return Result.error("添加失败，最低利润率限额应在0-100范围内！");
        }

        //新添加的商品设置为下架状态  by Kevin 20220227
        commodityManagement.setStatus("2");
        commodityManagement.setInventory(0);
        commodityManagement.setCommodityCode(getNewCode(storeId));


        commodityManagementService.save(commodityManagement);
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "商品管理-获取商品编码")
    @ApiOperation(value = "商品管理-获取商品编码", notes = "商品管理-获取商品编码")
    @GetMapping(value = "/commodityCode")
    public Result<?> commodityCode(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        return Result.OK(getNewCode(storeId));
    }

    private int getNewCode(String storeId) {
        QueryWrapper<CommodityManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        queryWrapper.orderByDesc("commodity_code").last("limit 1");
        CommodityManagement bean = commodityManagementService.getOne(queryWrapper);
        if (bean == null || bean.getCommodityCode() == null) {
            return 1;
        }
        return bean.getCommodityCode() + 1;
    }

    /**
     * 编辑
     */
    @AutoLog(value = "商品管理-编辑")
    @ApiOperation(value = "商品管理-编辑", notes = "商品管理-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CommodityManagement commodityManagement, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        // 当前店铺全部商品（除自己）
        List<CommodityManagement> list = commodityManagementService.list(new QueryWrapper<CommodityManagement>()
                .eq("store_id", storeId)
                .ne("id", commodityManagement.getId()));
        // list中与commodityManagement同名的商品个数
        long count = list.stream().filter(cm -> cm.getTradeName().equals(commodityManagement.getTradeName())).count();
        if (count > 0) {
            return Result.error("编辑失败，该店铺已有同名商品！");
        }
        if (commodityManagement.getProductPrice() < 0) {
            return Result.error("编辑失败，价格不能小于0！");
        }
        if (commodityManagement.getPriceCost() < 0) {
            return Result.error("编辑失败，成本价不能小于0！");
        }
        if (commodityManagement.getGrossRate() < 0 || commodityManagement.getGrossRate() > 100) {
            return Result.error("编辑失败，毛利率应在0-100范围内！");
        }
        if (commodityManagement.getMinimumMargin() < 0 || commodityManagement.getMinimumMargin() > 100) {
            return Result.error("编辑失败，最低利润率限额应在0-100范围内！");
        }
        commodityManagementService.updateById(commodityManagement);
        return Result.OK("编辑成功！");
    }

    /**
     * 通过id删除
     */
    @AutoLog(value = "商品管理-通过id删除")
    @ApiOperation(value = "商品管理-通过id删除", notes = "商品管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        commodityManagementService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     */
    @AutoLog(value = "商品管理-批量删除")
    @ApiOperation(value = "商品管理-批量删除", notes = "商品管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.commodityManagementService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     */
    @AutoLog(value = "商品管理-通过id查询")
    @ApiOperation(value = "商品管理-通过id查询", notes = "商品管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CommodityManagement commodityManagement = commodityManagementService.getById(id);
        if (commodityManagement == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(commodityManagement);
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CommodityManagement commodityManagement) {
        //return super.exportXls(request, commodityManagement, CommodityManagement.class, "商品管理");
        String token = TokenUtils.getTokenByRequest(request);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);

        // Step.1 组装查询条件
        QueryWrapper<CommodityManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, commodityManagement, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<CommodityManagement> pageList = commodityManagementService.list(queryWrapper);

        // Step.3 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "商品管理"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, CommodityManagement.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams("商品管理数据", "导出人:" + user.getRealname(), "商品管理");
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CommodityManagement.class);
    }

    /**
     * 修改商品状态（前端未调用）
     */
    @AutoLog(value = "修改商品状态")
    @ApiOperation(value = "修改商品状态", notes = "修改商品状态")
    @PutMapping(value = "/updateStatus")
    public Result<?> updateStatus(@RequestBody JSONObject json) {
        String status = json.getString("status");
        String id = json.getString("id");
        commodityManagementService.updateStatus(status, id);
        return Result.OK("修改成功!");
    }

    /**
     * 批量修改商品状态
     */
    @AutoLog(value = "批量修改商品状态")
    @ApiOperation(value = "批量修改商品状态", notes = "批量修改商品状态")
    @PutMapping(value = "/updateStatusBatch")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> updateStatusBatch(@RequestBody JSONObject json) {
        String status = json.getString("status");
        String ids = json.getString("ids");
        List<String> listId = Arrays.asList(ids.split(","));
        List<CommodityManagement> cmList = commodityManagementService.listByIds(listId);
        for (CommodityManagement cm : cmList) {
            String status1 = cm.getStatus();
            if (status1.equals(status)) {
                continue;
            }
            if ("2".equals(status1) && "1".equals(status)) {
                if (cm.getInventory() == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return Result.error("部分商品库存为0，不能上架，请重新选择！");
                }
            }
            cm.setStatus(status);
            commodityManagementService.updateById(cm);
        }

        return Result.OK("修改成功！");
    }

    /**
     * 批量修改商品分组
     */
    @AutoLog(value = "批量修改商品分组")
    @ApiOperation(value = "批量修改商品分组", notes = "批量修改商品分组")
    @PutMapping(value = "/updateGroupBatch")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> updateGroupBatch(@RequestBody JSONObject json) {
        String groupId = json.getString("groupId");
        String groupName = json.getString("groupName");
        String ids = json.getString("ids");
        String[] listId = ids.split(",");
        for (String id : listId) {
            CommodityManagement cm = new CommodityManagement();
            cm.setId(id);
            cm.setGroupId(groupId);
            cm.setClassificationGoods(groupName);
            commodityManagementService.updateById(cm);
        }

        return Result.OK("修改成功！");
    }

}
